package com.yami.shop.mystery.common.listener;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.yami.shop.bean.bo.*;
import com.yami.shop.bean.enums.DeliveryType;
import com.yami.shop.bean.enums.EsOperationType;
import com.yami.shop.bean.enums.ProdStatusEnums;
import com.yami.shop.bean.enums.ShopStatus;
import com.yami.shop.bean.event.EsMysteryBoxEvent;
import com.yami.shop.bean.model.Category;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.order.EsProductOrder;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.enums.StatusEnum;
import com.yami.shop.common.util.BeanUtil;
import com.yami.shop.dao.BrandMapper;
import com.yami.shop.dao.CategoryMapper;
import com.yami.shop.dao.ShopDetailMapper;
import com.yami.shop.mystery.common.dao.MysteryBoxMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 获取es商品盲盒数据事件
 *
 * @author wxf
 * @date 2023/4/13 12:01
 */
@Slf4j
@Component("mysteryBoxEsProductListener")
@AllArgsConstructor
public class EsProductListener {

    private final MysteryBoxMapper mysteryBoxMapper;

    private final CategoryMapper categoryMapper;

    private final ShopDetailMapper shopDetailMapper;

    private final BrandMapper brandMapper;

    @EventListener(EsMysteryBoxEvent.class)
    @Order(EsProductOrder.MYSTERBOX)
    public void mysteryBoxEsProductListener(EsMysteryBoxEvent event) {

        if (Objects.isNull(event.getOperationType())) {
            listEsProductData(event);
        } // 商品销量和库存数据
        else if (Objects.equals(event.getOperationType(), EsOperationType.UPDATE_SOLD_NUM)) {
            List<ProductBO> productList = mysteryBoxMapper.listEsProdSoldAndStock(event.getProdIds());
            for (ProductBO productBO : productList) {
                // 统计商品销量
                statisticsStock(productBO);
            }
            event.getProductList().addAll(productList);
        }
    }

    private void listEsProductData(EsMysteryBoxEvent event) {
        // 商品信息
        List<ProductBO> productList = mysteryBoxMapper.getProductBO(event.getProdIds());
        if (CollUtil.isEmpty(productList)) {
            return;
        }
        event.getProductList().addAll(productList);
        Set<Long> prodIds = new HashSet<>();
        Set<Long> categoryIds = new HashSet<>();
        List<Long> shopIds = new ArrayList<>();
        List<Long> brandIds = new ArrayList<>();
        for (ProductBO productBO : productList) {
            prodIds.add(productBO.getProdId());
            categoryIds.add(productBO.getCategoryId());
            categoryIds.add(productBO.getShopCategoryId());
            shopIds.add(productBO.getShopId());
            if (Objects.nonNull(productBO.getBrandId()) && productBO.getBrandId() > 0) {
                brandIds.add(productBO.getBrandId());
            }
            // 默认语言
            List<ProdLangBO> prodLangBOS = new ArrayList<>();
            ProdLangBO prodLangBO = new ProdLangBO();
            prodLangBO.setLang(0);
            prodLangBO.setProdName(productBO.getProdName());
            prodLangBOS.add(prodLangBO);
            productBO.setProdLangList(prodLangBOS);
        }

        // 商品分类信息
        List<Category> categories = categoryMapper.listAndParentByIds(categoryIds);
        Map<Long, Category> categoryMap = categories.stream().collect(Collectors.toMap(Category::getCategoryId, c -> c));
        // 商品店铺信息
        List<ShopDetail> shopDetails = shopDetailMapper.selectList(new LambdaQueryWrapper<ShopDetail>().in(ShopDetail::getShopId, shopIds));
        Map<Long, ShopDetail> shopMap = shopDetails.stream().collect(Collectors.toMap(ShopDetail::getShopId, s -> s));
        // 商品品牌信息
        Map<Long, BrandBO> brandMap;
        if (CollUtil.isEmpty(brandIds)) {
            brandMap = new HashMap<>(0);
        } else {
            List<BrandBO> brands = brandMapper.listAndLangBO(brandIds);
            brandMap = brands.stream().collect(Collectors.toMap(BrandBO::getBrandId, b -> b));
        }
        // 商品数据合并
        handEsProductData(productList, categoryMap, shopMap, brandMap);
    }

    private void handEsProductData(List<ProductBO> productList, Map<Long, Category> categoryMap, Map<Long, ShopDetail> shopMap, Map<Long, BrandBO> brandMap) {
        for (ProductBO productBO : productList) {
            try{
                productBO.setHasStock(Boolean.TRUE);
                if (Objects.isNull(productBO.getTotalStocks()) || Objects.equals(productBO.getTotalStocks(), 0)) {
                    productBO.setHasStock(Boolean.FALSE);
                }
                productBO.setAppDisplay(Boolean.TRUE);
                // 插入商品分类信息
                loadProdCategory(productBO, categoryMap, brandMap);
                // 插入商品店铺信息
                ShopDetail shopDetail = shopMap.get(productBO.getShopId());
                if (Objects.nonNull(shopDetail)) {
                    productBO.setShopName(shopDetail.getShopName());
                    productBO.setShopType(shopDetail.getType());
                    if (productBO.getAppDisplay() && !Objects.equals(shopDetail.getShopStatus(), ShopStatus.OPEN.value())) {
                        productBO.setAppDisplay(Boolean.FALSE);
                    }
                } else if (Objects.equals(productBO.getShopId(), Constant.PLATFORM_SHOP_ID)) {
                    productBO.setShopName(Constant.PLATFORM_SHOP_NAME);
                    productBO.setShopType(1);
                } else {
                    productBO.setAppDisplay(Boolean.FALSE);
                    log.error("商品数据异常(prodId:{})-店铺(shopId:{})不存在", productBO.getProdId(), productBO.getShopId());
                }
                // 商品数据处理
                loadProdData(productBO);
            } catch (Exception e) {
                log.error("商品数据异常:{}", productBO);
            }
        }
    }

    private void loadProdCategory(ProductBO productBO, Map<Long, Category> categoryMap, Map<Long, BrandBO> brandMap) {
        // 处理品牌信息
        BrandBO brand = brandMap.get(productBO.getBrandId());
        if (Objects.nonNull(brand)) {
            productBO.setBrandBO(brand);
        }

        // 平台分类信息
        Category category = categoryMap.get(productBO.getCategoryId());
        if (Objects.isNull(category)) {
            log.error("商品数据异常(prodId:{})-平台分类(category:{})不存在", productBO.getProdId(), productBO.getCategoryId());
            return;
        }
        CategoryBO categoryBO = new CategoryBO();
        categoryBO.setCategoryId(category.getCategoryId());
        categoryBO.setCategoryLangList(BeanUtil.mapAsList(category.getCategoryLangList(), CategoryLangBO.class));

        productBO.setCategoryId(category.getCategoryId());
        productBO.setCategory(categoryBO);
        if (productBO.getAppDisplay() && !Objects.equals(category.getStatus(), StatusEnum.ENABLE.value())) {
            productBO.setAppDisplay(Boolean.FALSE);
        }
        if (!categoryMap.containsKey(category.getParentId())) {
            return;
        }
        Category secondaryCategory = categoryMap.get(category.getParentId());
        productBO.setSecondaryCategoryId(secondaryCategory.getCategoryId());
        if (!categoryMap.containsKey(secondaryCategory.getParentId())) {
            return;
        }
        Category primaryCategory = categoryMap.get(secondaryCategory.getParentId());
        productBO.setPrimaryCategoryId(primaryCategory.getCategoryId());

    }

    private void loadProdData(ProductBO productBO) {
        // 统计商品销量
        statisticsStock(productBO);

        // 配送方式
        Gson gson = new Gson();
        Product.DeliveryModeVO deliveryModeVO = gson.fromJson(productBO.getDeliveryMode(), Product.DeliveryModeVO.class);
        List<Integer> deliveries = new ArrayList<>();
        /*if (Objects.nonNull(deliveryModeVO.getHasCityDelivery()) && deliveryModeVO.getHasCityDelivery()) {
            // 同城配送
            deliveries.add(DeliveryType.SAME_CITY.getValue());
        }
        if (Objects.nonNull(deliveryModeVO.getHasShopDelivery()) && deliveryModeVO.getHasShopDelivery()) {
            // 店铺配送
            deliveries.add(DeliveryType.EXPRESS.getValue());
        }
        if (Objects.nonNull(deliveryModeVO.getHasUserPickUp()) && deliveryModeVO.getHasUserPickUp()) {
            // 用户自提
            deliveries.add(DeliveryType.STATION.getValue());
        }*/
        productBO.setDeliveries(deliveries);

        if (productBO.getAppDisplay() && !Objects.equals(productBO.getStatus(), ProdStatusEnums.NORMAL.getValue()) && !Objects.equals(productBO.getStatus(), ProdStatusEnums.sellOut.getValue())) {
            productBO.setAppDisplay(Boolean.FALSE);
        }
        // 此字段不需要保存到es中（
        //productBO.setProdName(null);
        //productBO.setBrief(null);
    }

    private void statisticsStock(ProductBO productBO) {
        // 销量统计
        if (Objects.isNull(productBO.getWaterSoldNum())) {
            productBO.setWaterSoldNum(0);
        }
        if (Objects.isNull(productBO.getActualSoldNum())) {
            productBO.setActualSoldNum(0);
        }
        productBO.setSoldNum(productBO.getActualSoldNum() + productBO.getWaterSoldNum());
    }
}
